package net.vkits.controller;

import net.vkits.admin.domain.model.FakeUser;
import net.vkits.admin.domain.repository.FakeUserRepository;
import net.vkits.common.Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;

/**
 * Created by ethan-liu on 2017/2/8.
 */
@Controller
@RequestMapping("/FakeUsers")
public class FakeUsersController {
    private static final Logger logger = LoggerFactory.getLogger(FakeUsersController.class);

    @Resource
    private FakeUserRepository fakeUserRepository;

    @RequiresPermissions("system:sys_role:list")
    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView fakeUsers() {
        String username = Utils.getUsername(SecurityUtils.getSubject()).orElse("Null");
        ModelMap modelMap = new ModelMap();
        modelMap.put("treeview", "content");
        modelMap.put("sidebar", "FakeUsers");
        modelMap.put("currentUser",username);
        return new ModelAndView("/FakeUsers", modelMap);
    }

    @RequiresPermissions("system:sys_role:list")
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    @ResponseBody
    public Page<FakeUser> getFakeUsers(@PageableDefault(value = 10, sort = {"id"}, direction = Sort.Direction.DESC)Pageable pageable) {
        Page<FakeUser> fakeUsers = fakeUserRepository.findAll(pageable);
        logger.info("size is: {}", fakeUsers.getTotalElements());
        return fakeUsers;
    }

    @RequiresPermissions("system:sys_role:add")
    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public String addFakeUser(@RequestBody FakeUser fakeUser) {
        logger.info("add FakeUser: {}", fakeUser);
        fakeUserRepository.save(fakeUser);
        return "done";
    }

    @RequiresPermissions("system:sys_role:del")
    @RequestMapping(value ="/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public String delFakeUser(@PathVariable Long id) {
        logger.info("del QA: {}", id);
        fakeUserRepository.delete(id);
        return "done";
    }
}
